<?php

session_start();

if (isset($_POST["invio"])) {
  // path assoluto
  // TODO mettere basic autentication
  $puntatore = fopen(realpath("protected/pasx.txt"), "r");
  $trovato = 0;
  while ((!feof($puntatore)) && (!$trovato)) {
    $linea = fgets($puntatore);
    $trovato = stristr($linea, $_POST["userid"]);
    $puntatore++;
  }
  fclose($puntatore);
  list($nomeutente, $password, $uid, $expired, $timeout) = split("\|", $linea); //escape
  
  if (($trovato)  && ($_POST["passwd"] == trim($password)) && ((strtotime('now') < strtotime($expired) ) ) ){
    $_SESSION['start'] = time();
	$_SESSION['expire'] = $_SESSION['start'] + ($timeout);
    $_SESSION["autorizzato"] = 1;
    $_SESSION['uid']=$uid;
    $_SESSION['user']=$nomeutente;
    $destinazione = "vocabolario.php";
  } else {
    $destinazione = "loginfail.php";
  }
  echo '<script language=javascript>document.location.href="'.$destinazione.'"</script>';
} else {
?>
  <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
  <html>
  <head>
  <title>Login</title>
  <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
  <style type="text/css">
  body,td,th {
	font-family: Verdana, Geneva, sans-serif;
	font-size: 12px;
    }
  body {
	background-image: url(images/sfondo.jpg);
  }   
  </style>
  </head>
  <link rel="icon" href="images/favicon.png" type="image/png" />
  <body>
  <form method=post action="login.php">
    <p>&nbsp;</p>
    <table width="300" border="0" align="center" cellpadding="4" cellspacing="1">
      <tr>
        <td colspan="2" align="center"><img src="images/logo.jpg" ></td>
      </tr>
      <tr>
        <td colspan="2" align="center">&nbsp;</td>
      </tr>
      <tr>
        <td colspan="2" align="center">Inserire le credenziali per ottenere l'accesso<br>
      </tr>
      <tr>
        <td align="right">
          nome utente: 
        </td>
        <td>
          <input type="text" name="userid">
        </td>
      </tr>
      <tr>
        <td align="right">
          password: 
        </td>
        <td>
          <input type="password" name="passwd">
        </td>
      </tr>
      <tr>
        <td colspan="2" align="center">
          <input type="submit" name="invio" value="invio">
          &nbsp;&nbsp;
          <input type="reset" name="cancella" value="annulla">
        </td>
      </tr>
    </table>
    <br>
  </form>
  </body>
  </html>
<?php
}
?>